using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace HarrisDesigns.Controls.dasBlogControls.Twitter
{
    public class Status
    {
        [JsonProperty("created_at")]
        public string TimeStamp { get; set; }

        [JsonIgnore]
        public DateTime Created
        {
            get
            {
                string[] values = TimeStamp.Split(' ');
                string timeString = values[0] + ", " + values[2] + " " + values[1] + " " + values[5] + " " + values[3] + " GMT";
                return DateTime.Parse(timeString);
            }

            set { throw new NotImplementedException(); }
        }

        [JsonProperty("id")]
        public Int64 ID { get; set; }

        [JsonProperty("text")]
        public string Text { get; set; }

        [JsonProperty("source")]
        public string Source { get; set; }

        [JsonProperty("user")]
        public User User { get; set; }

        public string GetTextAsHtml()
        {
            string html = Text;
            html = ConvertUrlsToLinks(html);
            return ConvertMentionsToLinks(html);
        }

        public string ConvertMentionsToLinks(string html)
        {
            var atReplace = new Regex(@"\B@([_a-z0-9]+)", RegexOptions.IgnoreCase);
            return atReplace.Replace(html, @"<a href=""http://twitter.com/$1/"">@$1</a>");
        }

        public string ConvertUrlsToLinks(string html)
        {
            var linkReplace = new Regex(@"((https?|s?ftp|ssh)\:\/\/[^""\s\<\>]*[^.,;'"">\:\s\<\>\)\]\!])",
                                        RegexOptions.IgnoreCase);
            return linkReplace.Replace(html, @"<a href=""$1"">$1</a>");
        }

        public string GetTimeDifference()
        {
            TimeSpan diff = DateTime.Now - Created;
            if (diff.TotalSeconds < 60)
            {
                return "less than a minute ago";
            }
            if (diff.TotalMinutes < 2)
            {
                return "about a minute ago";
            }
            if (diff.TotalMinutes < 60)
            {
                return (int)diff.TotalMinutes + " minutes ago";
            }
            if (diff.TotalHours < 2)
            {
                return "about an hour ago";
            }
            if (diff.TotalHours < 24)
            {
                return (int)diff.TotalHours + " hours ago";
            }
            if (diff.TotalDays < 2)
            {
                return "1 day ago";
            }
            return (int)diff.TotalDays + " days ago";
        }
    }
}